package mylab.starters.mybatis.injector.methods;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

/**
 * @Description:
 * @author: Sylar
 * @date: 2021年10月08日 2:50 下午
 */
@Slf4j
public class UpdateBatch extends AbstractMethod {

    public static final String METHOD_NAME = "updateBatch";
    public static final String SQL = "<script>\n<foreach collection=\"list\" item=\"item\" separator=\";\">\nupdate %s %s where %s=#{%s} %s\n</foreach>\n</script>";
    static final String ITEM = "item";
    static final String ITEM_PREFIX = "item.";

    public UpdateBatch() {
        super(METHOD_NAME);
    }

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        String additional = tableInfo.isWithVersion()
                ? tableInfo.getVersionFieldInfo().getVersionOli(ITEM, ITEM_PREFIX)
                : "" + tableInfo.getLogicDeleteSql(true, true);
        String setSql = sqlSet(tableInfo.isWithLogicDelete(), false, tableInfo, false, ITEM, ITEM_PREFIX);
        String sqlResult = String.format(
                SQL,
                tableInfo.getTableName(),
                setSql,
                tableInfo.getKeyColumn(),
                ITEM_PREFIX + tableInfo.getKeyProperty(),
                additional);
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sqlResult, modelClass);
        return this.addUpdateMappedStatement(mapperClass, modelClass, METHOD_NAME, sqlSource);
    }

}
